package com.broadsoft.platform.wfengine.expression;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * FIXME: <A few lines of description of what class is about and what it does.>
 * 
 * <HR/>
 * <B>Modification Block</B>
 * <P>
 * Version: FIXME: 1.0.1 <BR>
 * Author: FIXME: luzhen Date: 2011-9-15 TAG: <A short name to find out all changed made by this modification.>
 * Comments: Created. Bug fix NO.: <If required>
 * </P>
 * <P>
 * ... Other Modifications following above structure.
 * </P>
 * 
 */
public class ExpressionHelper {

    private final static Logger logger = LoggerFactory.getLogger(ExpressionHelper.class);

    public static String executeExpression(String scriptText) {
        String retValue = "";
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
        try {
            String executionScript = generateMethodBlock(scriptText);
            jsEngine.eval(executionScript);
            Invocable invocableEngine = (Invocable) jsEngine;
            Object obj = invocableEngine.invokeFunction("invokeDecisionExpression");
            retValue = (String) obj;
            if (logger.isTraceEnabled()) {
                logger.trace("The local variable[retValue] is {}.", retValue);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return retValue;
    }

    private static String generateMethodBlock(String methodContent) {
        StringBuffer sbScript = new StringBuffer();
        sbScript.append(" function invokeDecisionExpression() { ");
        sbScript.append(methodContent);
        sbScript.append(" } ");
        return sbScript.toString();
    }
}
